# coding: UTF-8
# ----------
# Project_Name : pythonProject
# File_Name : huangcongbing
# Author : asus
# Date_Time:2022/4/23 17:32
# Description :
# ----------
# 实现京东的购物流程
# 打开京东，搜索商品，以销量排行，打开销量前5，切换到销量第二，上下翻页，选尺码，颜色，数量为5，加入购物车
# 点账号登录，输入账号密码，完成登录
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
def foo1():
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get('https://www.jd.com/?') #打开京东
    time.sleep(3)  #停留时间3秒

    driver.find_element(By.ID,'key').send_keys('T恤')#输入T恤、
    time.sleep(2)
    driver.find_element(By.ID,'key').send_keys(Keys.ENTER)#回车确定输入的内容
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="J_filter"]/div[1]/div[1]/a[2]').click()#用xpton定位销量，模拟鼠标点击
    time.sleep(3)
    #排序销量前五
    for i in range(1,6):
        driver.find_element(By.XPATH,f'//*[@id="J_goodsList"]/ul/li[{i}]/div').click()
        time.sleep(3)
   #获取打开页面的句柄
    handles = driver.window_handles
    print(handles)
    time.sleep(3)
    # 循环切换窗口至销量第二
    for handle in handles:
        driver.switch_to.window(handle)
        if driver.current_url =='https://item.jd.com/10030434646453.html':
            break
    #选择颜色、尺码、数量、翻页
    driver.find_element(By.XPATH,'/html').send_keys(Keys.PAGE_DOWN)#下翻页
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="choose-attr-1"]/div[2]/div[11]/a').click()  #选择颜色
    time.sleep(2)
    driver.find_element(By.XPATH, '/html').send_keys(Keys.PAGE_UP)  # 上翻页
    time.sleep(2)
    driver.find_element(By.XPATH, '//*[@id="choose-attr-2"]/div[2]/div[2]/a').click()  # 选择尺码
    time.sleep(2)
    driver.find_element(By.XPATH, '/html').send_keys(Keys.PAGE_DOWN)  # 下翻页
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="buy-num"]').clear()#清除原有的数量
    time.sleep(1)
    driver.find_element(By.XPATH,'//*[@id="buy-num"]').send_keys('5')#输入购买的数量
    time.sleep(2)
    #加入购物车
    driver.find_element(By.XPATH,'//*[@id="InitCartUrl"]').click()
    #登录
    driver.find_element(By.XPATH,'//*[@id="content"]/div[2]/div[1]/div/div[3]/a').click()#点击账号密码输入
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="loginname"]').clear()# 清除原有的账户
    time.sleep(1)
    driver.find_element(By.XPATH,'//*[@id="loginname"]').send_keys('tts123456')#输入账户
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="nloginpwd"]').clear()# 清除原有的密码
    time.sleep(1)
    driver.find_element(By.XPATH, '//*[@id="nloginpwd"]').send_keys('a123456789')#输入密码
    time.sleep(2)
    driver.find_element(By.XPATH,'//*[@id="loginsubmit"]').click()#模拟点击登录
    driver.quit()
if __name__ == "__main__":
        foo1()